package edu.gatech.angry12.UI.client;

import java.util.HashMap;

import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.PasswordTextBox;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.event.dom.client.KeyUpEvent;

/**
 * Login is a class that handles login functionality of Seed Swap Application.
 * 
 * @author Chris
 *
 */
public class Login extends Composite {
	private TextBox textBoxUserID;
	private PasswordTextBox textBoxPassword;
	private int loginFailCount;
	private HashMap<String, String> mapIDPW;

	public Login() {

        ////////////////////////////////////////
		////////// TESTING ACCOUNTS ///////////
		mapIDPW = new HashMap<String, String>();

		User defaultUser = new User("Angry Programmer", "defaultUser", "password");
		User user1 = new User("Angry Programmer 1", "user1", "password1");
		User user2 = new User("Angry Programmer 2", "user2", "password2");
		User user3 = new User("Angry Programmer 3", "user3", "password3");
		User user4 = new User("Angry Programmer 4", "user4", "password4");

		mapIDPW.put(defaultUser.getUserID(), defaultUser.getPassword());
		mapIDPW.put(user1.getUserID(), user1.getPassword());
		mapIDPW.put(user2.getUserID(), user2.getPassword());
		mapIDPW.put(user3.getUserID(), user3.getPassword());
		mapIDPW.put(user4.getUserID(), user4.getPassword());
		////////////////////////////////////////
    
		loginFailCount = 0;

		VerticalPanel verticalPanel = new VerticalPanel();
		verticalPanel.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
		verticalPanel.setStyleName("gwt-SeedApp-Login-background");
		initWidget(verticalPanel);
		verticalPanel.setSize("410px", "170px");

		Label lblSignIn = new Label("Please Sign In");
		verticalPanel.add(lblSignIn);

		FlexTable flexTable = new FlexTable();
		flexTable.setStyleName("gwt-Label-Login");
		verticalPanel.add(flexTable);
		flexTable.setWidth("350px");

		Label lblId = new Label("ID:");
		flexTable.setWidget(0, 0, lblId);

		textBoxUserID = new TextBox();
		flexTable.setWidget(0, 1, textBoxUserID);

		Label lblPassword = new Label("Password:");
		flexTable.setWidget(1, 0, lblPassword);

		textBoxPassword = new PasswordTextBox();
		textBoxPassword.addKeyUpHandler(new LogInHandler() );
		flexTable.setWidget(1, 1, textBoxPassword);

		Button btnSignIn = new Button("Sign In");
		btnSignIn.addClickHandler(new LogInHandler() );
		flexTable.setWidget(2, 1, btnSignIn);
	}

	/**
	 * LogInClickHandler is a private class that handles the event when Login button is clicked.
	 *  
	 * @author Chris
	 *
	 */
	private class LogInHandler extends SeedAppEntry implements ClickHandler, KeyUpHandler  {

		/**
		 * When a ClickEvent is fired, it checks whether ID and Password text fields are filled.
		 * If they are filled, it checks whether the ID and Password are correct.
		 *  
		 * @param event a ClickEvent fired when the login button is clicked
		 */
		public void onClick(ClickEvent event) {
			handleLogIn();
		}
		
		public void onKeyUp(KeyUpEvent event) {
			if (event.getNativeKeyCode()==KeyCodes.KEY_ENTER) {
				handleLogIn();
			}	
		}
		
		/**
		 * Handles the event when either Sign In button is clicked 
		 * or enter key is pressed in the password textbox 
		 */
		private void handleLogIn() {
			if (textBoxUserID.getText().length() == 0 && textBoxPassword.getText().length() != 0) {
				Window.alert("ID or password is empty."); 
			} else if (textBoxUserID.getText().length() == 0 && textBoxPassword.getText().length() != 0) {
				Window.alert("ID is empty.");
			} else if (textBoxUserID.getText().length() != 0 && textBoxPassword.getText().length() == 0) {
				Window.alert("Password is empty.");
			} else if (textBoxUserID.getText().length() == 0 && textBoxPassword.getText().length() == 0) {
				Window.alert("ID and password are empty.");
			} else {
				try {
					String id = textBoxUserID.getText().trim();
					String pw = textBoxPassword.getText().trim();

					if (!authenticate(id, pw) && loginFailCount==0) {
						loginFailCount++;
						Window.alert("Login failed. Make sure that your ID and/or password."); 
					} else if (!authenticate(id, pw) && loginFailCount>0 && loginFailCount<2) {
						loginFailCount++;
						Window.alert("Login trial " + loginFailCount + "/3 : Failed. \nPlease check your ID and/or password is wrong."); 
					} else if (authenticate(id, pw) && loginFailCount<3) {
						loginFailCount = 0;
						// SeedAppMain mainPage = new SeedAppMain();
						// toDisplay = new Home();
						// updateDisplay(new Home());
						Window.alert("Login Successful!"); 
					} else {
						loginFailCount++;
						Window.alert("Login trial " 
								+ loginFailCount + "/3 : Failed." 
								+ "\nYour account has been locked." + 
								"\nPlease contact the administrator to unlock your account.");
						loginFailCount=0; // initialize the count. need to be removed.
					}

				} catch (Exception ex) {
					// handle error
				} 
			}
		}
		
	}
	
	/*
	private class LogInKeyUpHandler implements KeyUpHandler  {
		
	}
	*/
	
	
	/**
	 * Checks whether the id and the password that the user input are correct.
	 * 
	 * @param id a String for id to check
	 * @param pw a String for password
	 * @return a boolean that indicates whether the login attempt was successful or not
	 */
	private boolean authenticate(String id, String pw) {
		if (mapIDPW.containsKey(id)) {
			return (mapIDPW.get(id).equals(pw) ? true : false);
		}					
		return false; 

	}



}
